<?php

namespace App\Service\WorkOrder\FunctionOpen;


use App\Enums\OpenShop\MissionTemplateEnum;
use App\Enums\WorkOrder\MissionEnum;
use App\Enums\WorkOrder\OrderEnum;
use App\Http\Form\AnalysisFormContent;
use App\Http\Form\Form;
use App\Http\Form\KfCashRegisterV2\KfCashRegisterV2FormAttribute;
use App\Jobs\FuYou\FuYouAutoJob;
use App\Models\Appraise\AppraiseModel;
use App\Models\Common\ResourcesModel;
use App\Models\FuYou\WorkOrderFuyouInfoModel;
use App\Models\Fy\FyRegionBankModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopMainProcessModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderModel;
use App\Models\System\SystemNotifyCenterModel;
use App\Models\WorkOrder\WorkOrderApplyContentModel;
use App\Models\WorkOrder\WorkOrderApplyMainModel;
use App\Models\WorkOrder\WorkOrderApplyManagerModel;
use App\Models\WorkOrder\WorkOrderMissionModel;
use App\Models\WorkOrder\WorkOrderOperateLogModel;
use App\Models\WorkOrder\WorkOrderRejectDetailModel;
use App\Models\WorkOrder\WorkOrderRejectModel;
use App\Models\WorkOrder\WorkOrderResetModel;
use App\Remote\Rms\RmsShopRemote;
use App\Remote\Rms\RmsUserRemote;
use App\Service\BaseService;
use App\Service\Common\SmsService;
use App\Service\FuYou\FuYouService;
use App\Service\OpenShop\Feishu\ConfigService;
use App\Service\System\SystemNotifyService;
use App\Service\WorkOrder\Message\SendFsService;
use App\Service\WorkOrder\Mission\AutoPassService;
use App\Service\WorkOrder\Mission\MissionEngineService;
use App\Service\WorkOrder\Reject\WorkOrderRejectService;
use Exception;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;

class FunctionOpenService extends BaseService
{

    /**
     * @param int $shopId
     * @return array[]|void
     * @throws Exception|GuzzleException
     */
    public static function preview(int $shopId)
    {
        try {
            //获取rms功能开通信息
            $rmsFunctionOpenDetail = RmsShopRemote::functionOpenDetail($shopId);
            //获取工单功能开通信息
            $applyMain = WorkOrderApplyMainModel::query()
                                                ->where("shopId", $shopId)
                                                ->where("problemPid", OrderEnum::PROBLEM_PID_5)
                                                ->whereIn("problemChildId", array_keys(OrderEnum::FUNCTION_OPEN))
                                                ->get();

            // 重置记录
            $resetProblemChildIds = WorkOrderResetModel::getProblemChildIdsByShopId($shopId);

            return [
                "functionOpenDetail" => collect($rmsFunctionOpenDetail["functionOpenDetail"])
                    ->map(function ($v) use ($applyMain, $resetProblemChildIds) {
                        $problemChildId = 0;
                        switch ($v["type"]) {
                            case "kfCash":
                                $detail2 = $applyMain->where("problemChildId", OrderEnum::PROBLEM_PID_5_CHILDREN_105)
                                                     ->first();
                                //只显示2.0工单入口
                                $detail         = $detail2;
                                $problemChildId = OrderEnum::PROBLEM_PID_5_CHILDREN_105;
                                /*$detail1 = $applyMain->where("problemChildId", OrderEnum::PROBLEM_PID_5_CHILDREN_100)
                                                     ->first();

                                if ($detail2 || (empty($detail1) || empty($detail1->workOrderNo))) {
                                    $detail         = $detail2;
                                    $problemChildId = OrderEnum::PROBLEM_PID_5_CHILDREN_105;
                                } else {
                                    $detail         = $detail1;
                                    $problemChildId = OrderEnum::PROBLEM_PID_5_CHILDREN_100;
                                }*/

                                break;
                            case "eleTakeaway":
                                $detail         = $applyMain->where("problemChildId",
                                    OrderEnum::PROBLEM_PID_5_CHILDREN_102)
                                                            ->first();
                                $problemChildId = OrderEnum::PROBLEM_PID_5_CHILDREN_102;

                                break;
                            case "tiktokTakeaway":
                                $detail         = $applyMain->where("problemChildId",
                                    OrderEnum::PROBLEM_PID_5_CHILDREN_104)
                                                            ->first();
                                $problemChildId = OrderEnum::PROBLEM_PID_5_CHILDREN_104;

                                break;
                            case "mtTakeaway":
                                $detail         = $applyMain->where("problemChildId",
                                    OrderEnum::PROBLEM_PID_5_CHILDREN_101)
                                                            ->first();
                                $problemChildId = OrderEnum::PROBLEM_PID_5_CHILDREN_101;

                                break;
                            case "mtGroupBuy":
                                $detail         = $applyMain->where("problemChildId",
                                    OrderEnum::PROBLEM_PID_5_CHILDREN_103)
                                                            ->first();
                                $problemChildId = OrderEnum::PROBLEM_PID_5_CHILDREN_103;

                                break;
                            default:
                                $detail = null;
                                break;
                        }
                        if ($detail) {
                            switch ($detail->step) {
                                case MissionEnum::STEP_1:
                                    $status = OrderEnum::MAIN_STATUS_CLOSE;
                                    break;
                                case MissionEnum::STEP_99:
                                case MissionEnum::STEP_100:
                                    $status = OrderEnum::MAIN_STATUS_FINISH;
                                    break;
                                default:
                                    $status = OrderEnum::MAIN_STATUS_ING;
                                    break;
                            }
                        } else {
                            $status = OrderEnum::MAIN_STATUS_CLOSE;
                        }

                        // 没重置过 - 工单、rms绑定取 或的关系
                        if (!in_array($problemChildId, $resetProblemChildIds)) {
                            if ($v["isOpen"]) {
                                $status = OrderEnum::MAIN_STATUS_FINISH;
                            }
                        }

                        return [
                            "type"           => $v["type"],
                            "status"         => $status,
                            'childStep'      => $detail->childStep ?? 0,
                            'problemPid'     => OrderEnum::PROBLEM_PID_5,
                            'problemChildId' => $problemChildId,
                            'workOrderNo'    => $detail->workOrderNo ?? '',
                        ];
                    })
            ];

        } catch (Exception $exception) {
            handleException($exception);
        }
    }

    /**
     * @param int $type
     * @param int $shopId
     * @param int $uid
     * @return array[]|void
     * @throws Exception|GuzzleException
     */
    public static function formContent(int $type, int $shopId, int $uid)
    {
        try {


            $parentType = OrderEnum::PROBLEM_PID_5;
            //获取rms功能开通信息
            $rmsFunctionOpenDetail           = RmsShopRemote::functionOpenDetail($shopId);
            $rmsFunctionOpenDetailCollection = collect($rmsFunctionOpenDetail["functionOpenDetail"]);
            //获取功能开通申请信息
            $applyMainAll = WorkOrderApplyMainModel::query()->where("shopId", $shopId)
                                                   ->where("problemPid", OrderEnum::PROBLEM_PID_5)
                                                   ->whereIn("problemChildId", array_keys(OrderEnum::FUNCTION_OPEN))
                                                   ->get();


            $nowRmsTypeFunctionOpen = [];

            $workOrderNo = $completeTime = "";

            collect(OrderEnum::FUNCTION_OPEN)
                ->when($type == OrderEnum::PROBLEM_PID_5_CHILDREN_105, function (Collection $v) {
                    return $v->except(OrderEnum::PROBLEM_PID_5_CHILDREN_100);
                })->when($type == OrderEnum::PROBLEM_PID_5_CHILDREN_100, function (Collection $v) {
                    return $v->except(OrderEnum::PROBLEM_PID_5_CHILDREN_105);
                })->keys()
                ->each(function ($functionOpenType) use (
                    $applyMainAll,
                    $rmsFunctionOpenDetailCollection,
                    $shopId,
                    $uid,
                    $type,
                    &$nowRmsTypeFunctionOpen,
                    $parentType,
                    &$workOrderNo,
                    &$completeTime
                ) {
                    $applyMain = $applyMainAll->where("problemChildId", $functionOpenType)->first();
                    if ($functionOpenType == $type) {
                        $workOrderNo  = $applyMain->workOrderNo ?? "";
                        $completeTime = $applyMain->completeTime ?? "";
                    }
                    switch ($functionOpenType) {
                        /*case OrderEnum::PROBLEM_PID_5_CHILDREN_100:
                            $rmsTypeOpen = $rmsFunctionOpenDetailCollection->where("type", "kfCash")->first();
                            if (in_array($type,
                                [OrderEnum::PROBLEM_PID_5_CHILDREN_100, OrderEnum::PROBLEM_PID_5_CHILDREN_105])) {
                                $nowRmsTypeFunctionOpen = $rmsTypeOpen;
                            }
                            if ($applyMainAll->where("problemChildId", OrderEnum::PROBLEM_PID_5_CHILDREN_105)
                                             ->isEmpty()) {
                                if (!$rmsTypeOpen["isOpen"] && !$applyMain) {
                                    $applyMainModel = WorkOrderApplyMainModel::getOrCreateApplyMain($shopId,
                                        $parentType,
                                        $functionOpenType, $uid);
                                    WorkOrderApplyContentModel::getOrCreateFunctionOpenApplyContent(
                                        $applyMainModel->workOrderNo,
                                        $uid,
                                        $shopId
                                    );
                                }
                            }
                            break;*/
                        case OrderEnum::PROBLEM_PID_5_CHILDREN_105:
                            $rmsTypeOpen = $rmsFunctionOpenDetailCollection->where("type", "kfCash")->first();
                            if (in_array($type,
                                [OrderEnum::PROBLEM_PID_5_CHILDREN_100, OrderEnum::PROBLEM_PID_5_CHILDREN_105])) {
                                $nowRmsTypeFunctionOpen = $rmsTypeOpen;
                            }
                            if ($applyMainAll->where("problemChildId", OrderEnum::PROBLEM_PID_5_CHILDREN_105)
                                             ->isEmpty()) {
                                if (!$rmsTypeOpen["isOpen"] && !$applyMain) {
                                    $applyMainModel = WorkOrderApplyMainModel::getOrCreateApplyMain($shopId,
                                        $parentType,
                                        $functionOpenType, $uid);
                                    WorkOrderApplyContentModel::getOrCreateFunctionOpenApplyContent(
                                        $applyMainModel->workOrderNo,
                                        $uid,
                                        $shopId
                                    );
                                }
                            }
                            break;
                        case OrderEnum::PROBLEM_PID_5_CHILDREN_102:
                            $rmsTypeOpen = $rmsFunctionOpenDetailCollection->where("type", "eleTakeaway")->first();
                            if ($type == $functionOpenType) {
                                $nowRmsTypeFunctionOpen = $rmsTypeOpen;
                            }
                            if (!$rmsTypeOpen["isOpen"] && !$applyMain) {
                                $applyMainModel = WorkOrderApplyMainModel::getOrCreateApplyMain($shopId, $parentType,
                                    $functionOpenType, $uid);
                                WorkOrderApplyContentModel::getOrCreateFunctionOpenApplyContent(
                                    $applyMainModel->workOrderNo,
                                    $uid,
                                    $shopId
                                );
                            }
                            break;
                        case OrderEnum::PROBLEM_PID_5_CHILDREN_104:
                            $rmsTypeOpen = $rmsFunctionOpenDetailCollection->where("type", "tiktokTakeaway")
                                                                           ->first();
                            if ($type == $functionOpenType) {
                                $nowRmsTypeFunctionOpen = $rmsTypeOpen;
                            }
                            if (!$rmsTypeOpen["isOpen"] && !$applyMain) {
                                $applyMainModel = WorkOrderApplyMainModel::getOrCreateApplyMain($shopId, $parentType,
                                    $functionOpenType, $uid);
                                WorkOrderApplyContentModel::getOrCreateFunctionOpenApplyContent(
                                    $applyMainModel->workOrderNo,
                                    $uid,
                                    $shopId
                                );
                            }
                            break;
                        case OrderEnum::PROBLEM_PID_5_CHILDREN_101:
                            $rmsTypeOpen = $rmsFunctionOpenDetailCollection->where("type", "mtTakeaway")->first();
                            if ($type == $functionOpenType) {
                                $nowRmsTypeFunctionOpen = $rmsTypeOpen;
                            }
                            if (!$rmsTypeOpen["isOpen"] && !$applyMain) {
                                $applyMainModel = WorkOrderApplyMainModel::getOrCreateApplyMain($shopId, $parentType,
                                    $functionOpenType, $uid);
                                WorkOrderApplyContentModel::getOrCreateFunctionOpenApplyContent(
                                    $applyMainModel->workOrderNo,
                                    $uid,
                                    $shopId
                                );
                            }
                            break;
                        case OrderEnum::PROBLEM_PID_5_CHILDREN_103:
                            $rmsTypeOpen = $rmsFunctionOpenDetailCollection->where("type", "mtGroupBuy")->first();
                            if ($type == $functionOpenType) {
                                $nowRmsTypeFunctionOpen = $rmsTypeOpen;
                            }
                            if (!$rmsTypeOpen["isOpen"] && !$applyMain) {
                                $applyMainModel = WorkOrderApplyMainModel::getOrCreateApplyMain($shopId, $parentType,
                                    $functionOpenType, $uid);
                                WorkOrderApplyContentModel::getOrCreateFunctionOpenApplyContent(
                                    $applyMainModel->workOrderNo,
                                    $uid,
                                    $shopId
                                );
                            }
                            break;
                    }
                });


            // 重置记录
            $resetProblemChildIds = WorkOrderResetModel::getProblemChildIdsByShopId($shopId);

            // 没重置过的按老逻辑实现
            if (!in_array($type, $resetProblemChildIds)) {

                if (isset($nowRmsTypeFunctionOpen['isOpen']) && $nowRmsTypeFunctionOpen['isOpen']) {

                    $appraiseModel = AppraiseModel::getInfoByWorkOrderNo($workOrderNo);//评价反馈详情

                    $response       = [
                        "id"           => 0,
                        "status"       => OrderEnum::MAIN_STATUS_FINISH,
                        'childStep'    => MissionEnum::CHILD_STEP_0,
                        "workOrderNo"  => $workOrderNo,
                        "applyTime"    => formatDate($rmsTypeOpen["time"] ?? 0, ""),
                        "finishTime"   => formatDate($rmsTypeOpen["time"] ?? 0, ""),
                        "step"         => MissionEnum::STEP_99,
                        "formDesc"     => "",
                        "formContent"  => [],
                        'appraiseId'   => $appraiseModel ? $appraiseModel->id : 0,
                        'completeTime' => formatDate($completeTime),
                        "statusData"   => Form::getStatusData(null, OrderEnum::MAIN_STATUS_FINISH, $workOrderNo),
                    ];
                    $formContentObj = null;

                    return array_merge($response,
                        ["popDetail" => self::getFormPopContent($type, $shopId, $formContentObj)]);
                }
            }

            list($response, $formContentObj) =
                Form::getFormContentByShopIdAndType($shopId, OrderEnum::PROBLEM_PID_5, $type, $uid);

            // 收银工单申请需要加个限制：未落址的门店不允许申请工单，提示此门店还未落址
            $response['isNotSite'] = 0;// 默认0 1-未落址 不可提交表单

            $mainProcess = OpenShopMainProcessModel::getMainOrder($shopId);
            if ($mainProcess && $mainProcess->nowStepStatus < MissionTemplateEnum::STEP_STATUS_6 && $response['status'] == OrderEnum::MAIN_STATUS_CLOSE) {
                $response['isNotSite'] = 1;
            }

            return array_merge($response, ["popDetail" => self::getFormPopContent($type, $shopId, $formContentObj)]);
        } catch (Exception $exception) {
            handleException($exception);
        }
    }

    /**
     * @param int $type
     * @param int $shopId
     * @param AnalysisFormContent|null $analysisFormContent
     * @return array
     * @throws GuzzleException
     */
    public static function getFormPopContent(
        int $type,
        int $shopId,
        AnalysisFormContent $analysisFormContent = null
    ): array {
        $popContent = [
            "pop"        => false,
            "popContent" => [
                "1、建议门店堂食正式营业2周左右，出餐、人员稳定的情况下，再申请开通外卖",
                "2、为保障门店外卖运营效果，请您在申请外卖平台开通前联系督导或者外卖运营进行上线评估，评估通过后再提交申请"
            ]
        ];

        if (
            in_array($type, [OrderEnum::PROBLEM_PID_5_CHILDREN_101, OrderEnum::PROBLEM_PID_5_CHILDREN_102])
            &&
            $analysisFormContent instanceof AnalysisFormContent
            &&
            empty($analysisFormContent->getField("evaluationScreenshot", ""))
        ) {

            $shopSupervisorName       = $shopSupervisorMobile = "";
            $openShopMainProcessModel = OpenShopMainProcessModel::query()
                                                                ->where("shopId",
                                                                    $shopId)
                                                                ->where("childLocationOrder",
                                                                    0)
                                                                ->with([
                                                                    "signOrderRel" => function ($query) {
                                                                        $query->with(["checkAcceptRel"]);
                                                                    }
                                                                ])
                                                                ->first();

            if ($openShopMainProcessModel && $openShopMainProcessModel->signOrderRel && $openShopMainProcessModel->signOrderRel->checkAcceptRel) {
                $shopSupervisorName = $openShopMainProcessModel->signOrderRel->checkAcceptRel->managerName ?? "";
                $shopSupervisorUid  = $openShopMainProcessModel->signOrderRel->checkAcceptRel->managerId ?? 0;
                if ($shopSupervisorUid > 0) {
                    $userInfo             = RmsUserRemote::getRmsUserByIds([$shopSupervisorUid]);
                    $shopSupervisorMobile = collect($userInfo)->keyBy("id")
                                                              ->get($shopSupervisorUid, [])["mobile"] ?? "";
                }
            }

            $popContent = array_merge(
                $popContent,
                [
                    "pop"        => true,
                    "popContent" => [
                        "1、建议门店堂食正式营业2周左右，出餐、人员稳定的情况下，再申请开通外卖",
                        $shopSupervisorMobile && $shopSupervisorName ?
                            "2、为保障门店外卖运营效果，请您在申请外卖平台开通前联系督导或者外卖运营进行上线评估，评估通过后再提交申请，督导联系方式： {$shopSupervisorMobile}  {$shopSupervisorName}"
                            :
                            "2、为保障门店外卖运营效果，请您在申请外卖平台开通前联系督导或者外卖运营进行上线评估，评估通过后再提交申请"
                    ]
                ]
            );
        }

        return $popContent;
    }


    /**
     * @param int $id
     * @param string $field
     * @param $value
     * @return void
     * @throws Exception
     */
    public static function saveField(int $id, string $field, $value)
    {
        try {
            Form::saveField($id, $field, $value);
        } catch (Exception $exception) {
            handleException($exception);
        }
    }

    /**
     * @param int $id
     * @param array $fields
     * @return array|void
     * @throws Exception
     */
    public static function saveFields(int $id, array $fields)
    {
        try {
            return Form::saveFields($id, $fields);
        } catch (Exception $exception) {
            handleException($exception);
        }
    }


    /**
     * @param int $id
     * @param int $uid
     * @return array|void
     * @throws ValidationException
     */
    public static function submitForm(int $id, int $uid)
    {
        // TODO workOrderNo校验
        $workOrderNo = (string)WorkOrderApplyContentModel::query()->where('id', $id)->value('workOrderNo');
        $applyMain   = WorkOrderApplyMainModel::query()->where('workOrderNo', $workOrderNo)->first();

        try {
            list($applyContent, $resources, $validateErrorFields) = Form::submitFormById($id);
//            dd($applyContent);
//            $validateErrorFields = [];
//            $applyContent        = WorkOrderApplyContentModel::query()->where("id", $id)->first();

            if (empty($validateErrorFields)) {

                // 常规新增工单
                if ($applyMain->step == MissionEnum::STEP_1) {
                    WorkOrderApplyMainModel::query()->where("workOrderNo", $applyContent->workOrderNo)->update(
                        [
                            "createdAt"    => time(),
                            "status"       => OrderEnum::MAIN_STATUS_ING,
                            "createdByUid" => $uid,
                        ]
                    );

                    //日志 - 提交工单
                    WorkOrderOperateLogModel::generateOperateLog(
                        $workOrderNo,
                        MissionEnum::STEP_1,
                        WorkOrderOperateLogModel::TYPE_1,
                        request()->user()->username,
                        request()->user()->id,
                        vsprintf("%s - %s", [
                            OrderEnum::PROBLEM_PID_TEXT[$applyMain->problemPid] ?? "",
                            OrderEnum::TYPE_RELATION_MAP[$applyMain->problemPid][$applyMain->problemChildId] ?? "",
                        ])
                    );

                    (new MissionEngineService($applyContent->workOrderNo))->finish(MissionEnum::STEP_1);

                    if ($applyMain->isFunctionWaiMaiOpen()){
                        AutoPassService::waiMaiOpenKeFuPass($applyMain);
                    }

                } elseif ($applyMain->childStep == MissionEnum::CHILD_STEP_1) {
                    $params     = json_decode($applyContent->content, true);
                    $resources  = (array)$resources;
                    $logContent = [
                        "parentType" => OrderEnum::PROBLEM_PID_TEXT[$applyMain->problemPid] ?? "",
                        "childType"  => OrderEnum::TYPE_RELATION_MAP[$applyMain->problemPid][$applyMain->problemChildId] ?? "",
                        "diff"       => []
                    ];

                    $lastReject = WorkOrderRejectModel::query()
                                                      ->with([
                                                          "detailsRel" => function ($query) {
                                                              $query->withoutGlobalScope("isDel");
                                                          }
                                                      ])
                                                      ->where("workOrderNo", $workOrderNo)
                                                      ->where("status", WorkOrderRejectModel::STATUS_INIT)
                                                      ->first();

                    if ($lastReject) {
                        $lastReject->detailsRel->each(function (
                            WorkOrderRejectDetailModel $orderRejectDetailModel
                        ) use ($params, $resources, &$logContent) {
                            $temp["field"]            = $orderRejectDetailModel->field;
                            $temp["fieldText"]        = $orderRejectDetailModel->fieldText;
                            $temp["fieldValue"]       = [
                                "before" => $orderRejectDetailModel->fieldValue,
                                "after"  => null
                            ];
                            $temp["reasonOptionText"] = $orderRejectDetailModel->reasonOptionText;
                            $temp["isResource"]       = 0;
                            if (isset($params[$orderRejectDetailModel->field])) {
                                $temp["fieldValue"]["after"] = $params[$orderRejectDetailModel->field];
                            }
                            if (isset($resources[$orderRejectDetailModel->field])) {
                                $temp["isResource"]           = 1;
                                $temp["fieldValue"]["before"] = json_decode($temp["fieldValue"]["before"], true);
                                $temp["fieldValue"]["after"]  = collect($resources[$orderRejectDetailModel->field])
                                    ->map(function (
                                        $resource
                                    ) {
                                        return picturePath($resource);
                                    })->values()->toArray();
                            }
                            array_push($logContent["diff"], $temp);
                        });
                    }

                    // 删除驳回状态
                    $lastRejectUserId = (new WorkOrderRejectService($workOrderNo))->fixReject($uid);

                    //日志 - 提交工单
                    WorkOrderOperateLogModel::generateOperateLog(
                        $workOrderNo,
                        MissionEnum::STEP_1,
                        WorkOrderOperateLogModel::TYPE_13,
                        request()->user()->username,
                        request()->user()->id,
                        json_encode($logContent, JSON_UNESCAPED_UNICODE)
                    );

                    // 驳回修改 - 通知处理人
                    if ($lastRejectUserId) {
                        (new SendFsService($workOrderNo))->kfDistributeProcessor(0, [$lastRejectUserId]);
                    }
                }
                //富友自动进件
                if ($applyMain->problemChildId == OrderEnum::PROBLEM_PID_5_CHILDREN_105) {
                    //判断是否是第一次提交-富友商户信息表
//                    $fuYouService = new FuYouService();
//                    $getInfo      = WorkOrderFuyouInfoModel::getInfoByWorkOrderNo($workOrderNo);
//                    if ($getInfo) {
//                        $fuYouService->wxMchntUpd(['workOrderNo' => $workOrderNo, 'id' => $id, 'shopId' => $applyMain->shopId]);//商户信息更新接口
//                    } else {
//                        $fuYouService->wxMchntAdd(['workOrderNo' => $workOrderNo, 'id' => $id, 'shopId' => $applyMain->shopId]);//商户信息登记接口
//                    }
                    dispatch((new FuYouAutoJob([
                        'workOrderNo' => $workOrderNo,
                        'id'          => $id,
                        'shopId'      => $applyMain->shopId
                    ])))->onQueue('{fuyou-auto}');
                }
            }

            return [
                "validateErrorFields" => $validateErrorFields
            ];

        } catch (Exception $exception) {
            handleException($exception);
        }
    }

    /**
     * 工单流程后续操作钩子方法
     *
     * @param WorkOrderApplyMainModel $applyMainModel
     * @param int $step
     * @throws GuzzleException
     */
    public static function hook(WorkOrderApplyMainModel $applyMainModel, int $step)
    {
        try {
            if ($step == MissionEnum::STEP_99 && $applyMainModel->problemPid == OrderEnum::PROBLEM_PID_5) {
                //收银工单完成自动提交商户通功能闭包
                $autoSubmitMtLinkForm = function () use ($applyMainModel) {
                    if (
                        $applyMainModel->problemPid == OrderEnum::PROBLEM_PID_5
                        &&
                        in_array($applyMainModel->problemChildId,
                            [OrderEnum::PROBLEM_PID_5_CHILDREN_100, OrderEnum::PROBLEM_PID_5_CHILDREN_105])
                    ) {
                        $mtLinkApplyModel = WorkOrderApplyMainModel::query()
                                                                   ->where("shopId", $applyMainModel->shopId)
                                                                   ->where("problemChildId",
                                                                       OrderEnum::PROBLEM_PID_5_CHILDREN_103)
                                                                   ->first();

                        if ($mtLinkApplyModel && $mtLinkApplyModel->step == MissionEnum::STEP_1) {
                            switch ($applyMainModel->problemChildId) {
                                case OrderEnum::PROBLEM_PID_5_CHILDREN_100:
                                    //同步收银进件数据到美团商户通
                                    WorkOrderApplyContentModel::query()
                                                              ->where("workOrderNo", $mtLinkApplyModel->workOrderNo)
                                                              ->update([
                                                                  "content" => $applyMainModel->contentRel->content
                                                              ]);

                                    //删除商户通原始资源信息
                                    ResourcesModel::query()
                                                  ->where("businessId", $mtLinkApplyModel->contentRel->id)
                                                  ->where("business", "FUNCTION_OPEN")
                                                  ->where("module", "WORK_ORDER")
                                                  ->update(["isDeleted" => 1]);

                                    //同步资源信息
                                    $originalResource = ResourcesModel::query()
                                                                      ->where("businessId",
                                                                          $applyMainModel->contentRel->id)
                                                                      ->where("isDeleted", 0)
                                                                      ->where("business", "FUNCTION_OPEN")
                                                                      ->where("module", "WORK_ORDER")
                                                                      ->get();


                                    ResourcesModel::query()->insert(
                                        $originalResource->map(function ($v) use ($mtLinkApplyModel) {
                                            return
                                                [
                                                    "businessId" => $mtLinkApplyModel->contentRel->id,
                                                    "module"     => $v->module,
                                                    "name"       => $v->name,
                                                    "url"        => $v->url,
                                                    "isPublic"   => $v->isPublic,
                                                    "sort"       => $v->sort,
                                                    "extra"      => $v->extra,
                                                ];
                                        })->toArray()
                                    );
                                    break;
                                case OrderEnum::PROBLEM_PID_5_CHILDREN_105:
                                    $content  = json_decode($applyMainModel->contentRel->content, true);
                                    $isPublic = $content["settlementType"] == KfCashRegisterV2FormAttribute::SETTLEMENT_TYPE_PUBLIC;
                                    $common   = [
                                        //证照信息
//                                        "businessLicenseImg" => $content["businessLicenseImg"] ?? "",
                                        "enterpriseName"        => $content["enterpriseName"] ?? "",
                                        "businessLicenseNumber" => $content["businessLicenseNumber"] ?? "",
                                        //营业执照-注册日期至结束日期
                                        "effectiveTime"                     => ($contentArray['businessLicenseRegistrationDate'] ?? "") . '-' .
                                            ($contentArray['businessLicenseEndDate'] ?? "2099-12-31"),//$content["businessLicenseValidityPeriod"] ?? "",
                                        "businessLicenseRegistrationDate"   => $content["businessLicenseRegistrationDate"] ?? "",
                                        "businessLicenseValidityPeriodType" => $content["businessLicenseValidityPeriodType"] ?? "",
                                        "businessLicenseEndDate"            => $content["businessLicenseEndDate"] ?? "",
                                        "businessPremises"      => $content["businessPremises"] ?? "",
                                        //首款信息
                                        "collectionType"        => $content["settlementType"] ?? "",
//                                        "bankCardImgFront" => $content["legalPersonBankCardFrontImg"] ?? "",
                                        "collectionBankAccount" => $isPublic ? $content["companyBankCardNumber"] ?? "" : $content["legalPersonBankCardNumber"] ?? "",
                                        "accountBank"           => $isPublic ? $content["companyBankCardNumber"] ?? "" : $content["legalPersonBankCardNumber"] ?? "",
                                        "provinceBank"          => $isPublic ?
                                            ($content["companyBankCardBankArea"] ? $content["companyBankCardBankArea"]["addressPrefix"] : "")
                                            :
                                            ($content["legalPersonBankCardBankArea"] ? $content["legalPersonBankCardBankArea"]["addressPrefix"] : "")
                                        ,
                                        "accountBranchBank"     => $isPublic ?
                                            FyRegionBankModel::query()
                                                             ->where("bankNo", $content["companyBankCardBranchBank"])
                                                             ->first()->name
                                            :
                                            FyRegionBankModel::query()->where("bankNo",
                                                $content["legalPersonBankCardBranchBank"])->first()->name,
                                        "bankReserveMobile"     => $isPublic ? $content["companyBankCardReserveMobile"] ?? "" : $content["legalPersonBankCardReserveMobile"] ?? "",
//                                        "collectionPersonIdentityCardFront" => $content["legalPersonIdentityCardFront"] ?? "",
//                                        "collectionPersonIdentityCardBack" => $content["legalPersonIdentityCardBack"] ?? "",

                                        "collectionPersonUsername"                   => $content["legalPersonUsername"] ?? "",
                                        "collectionPersonIdentityCardNumber"         => $content["legalPersonIdentityCardNumber"] ?? "",
                                        "collectionPersonIdentityCardValidityPeriod" => $content["legalPersonIdentityCardValidityPeriod"] ?? "",
                                    ];

                                    WorkOrderApplyContentModel::query()
                                                              ->where("workOrderNo", $mtLinkApplyModel->workOrderNo)
                                                              ->update([
                                                                  "content" => json_encode(array_merge(json_decode($applyMainModel->contentRel->content,
                                                                      true), $common), JSON_UNESCAPED_UNICODE)
                                                              ]);

                                    //删除商户通原始资源信息
                                    ResourcesModel::query()
                                                  ->where("businessId", $mtLinkApplyModel->contentRel->id)
                                                  ->where("business", "FUNCTION_OPEN")
                                                  ->where("module", "WORK_ORDER")
                                                  ->update(["isDeleted" => 1]);

                                    //同步资源信息
                                    $originalResource = ResourcesModel::query()
                                                                      ->where("businessId",
                                                                          $applyMainModel->contentRel->id)
                                                                      ->where("isDeleted", 0)
                                                                      ->where("business", "FUNCTION_OPEN")
                                                                      ->where("module", "WORK_ORDER")
                                                                      ->get();


                                    ResourcesModel::query()->insert(
                                        $originalResource->map(function ($v) use ($mtLinkApplyModel) {
                                            switch ($v->name) {
                                                case "legalPersonBankCardFrontImg":
                                                    $name = "bankCardImgFront";
                                                    break;
                                                case "legalPersonIdentityCardFront":
                                                    $name = 'collectionPersonIdentityCardFront';
                                                    break;
                                                case "legalPersonIdentityCardBack":
                                                    $name = "collectionPersonIdentityCardBack";
                                                    break;
                                                default:
                                                    $name = $v->name;
                                                    break;
                                            }
                                            return
                                                [
                                                    "businessId" => $mtLinkApplyModel->contentRel->id,
                                                    "module"     => $v->module,
                                                    "business"   => $v->business,
                                                    "name"       => $name,
                                                    "url"        => $v->url,
                                                    "isPublic"   => $v->isPublic,
                                                    "sort"       => $v->sort,
                                                    "extra"      => $v->extra,
                                                ];
                                        })->toArray()
                                    );
                                    break;
                            }


                            //提交
                            WorkOrderApplyMainModel::query()->where("workOrderNo", $mtLinkApplyModel->workOrderNo)
                                                   ->update([
                                                       "createdAt" => time(),
                                                       "status"    => OrderEnum::MAIN_STATUS_ING
                                                   ]);
                            (new MissionEngineService($mtLinkApplyModel->workOrderNo))->finish(MissionEnum::STEP_1);
                        }
                    }
                };

                //工单完成 - 门店消息发送闭包
                $shopMsgSend = function () use ($applyMainModel) {
                    $pushUidMap = array_values(
                        array_column(
                            (RmsUserRemote::getShopManagerUserByShopId([$applyMainModel->shopId])['lists'] ?? []),
                            "userId"
                        )
                    );

                    SystemNotifyService::customerBatchPush(
                        $pushUidMap,
                        '您提交的工单有内容需要修改',
                        "尊敬的夸父伙伴您好，您提交的工单（ID：{$applyMainModel->workOrderNo}）客服已处理完成，请登录夸父商家\"门店-问题反馈-反馈进度\"查看处理。",
                        OrderEnum::getDetailUrl($applyMainModel),
                        $applyMainModel->shopId,
                        SystemNotifyCenterModel::NOTIFY_TYPE_5
                    );
                };

                //收银进件提交，自动提交商户通表单
                $autoSubmitMtLinkForm();

                //门店消息发送
                //$shopMsgSend();
            }
        } catch (Exception $exception) {
            logException("工单钩子执行失败", $exception, $applyMainModel->toArray(), true, true);
        }
    }


    /**
     * 校验工单是否存在
     *
     * @param int $shopId
     * @param int $pid
     * @param int $cid
     * @return bool
     */
    public static function checkWorkOrderExist(int $shopId, int $pid, int $cid)
    {
        return WorkOrderApplyMainModel::query()
                                      ->where('shopId', $shopId)
                                      ->where('problemPid', $pid)
                                      ->where('problemChildId', $cid)
                                      ->where('step', '>', 1)
                                      ->exists();
    }


    /**
     * @param object $params
     * @return array|void
     * @throws Exception
     */
    public static function fyRegionBank(object $params)
    {
        try {
            $cacheKey = vsprintf("%s:%s:%s", [
                __CLASS__,
                __FUNCTION__,
                md5(collect((array)$params)->toJson(JSON_UNESCAPED_UNICODE))
            ]);

            $fyRegionBankFunc = function () use ($params) {
                $fyRegionBankData = FyRegionBankModel::getBankNo($params->bankTypeCode, $params->regionBankCode);
                if (!$fyRegionBankData && isset($params->parentId) && $params->parentId) {
                    $fyRegionBankData = FyRegionBankModel::getBankNo($params->bankTypeCode, $params->parentId);
                }
                return $fyRegionBankData;
            };

            $ttl = 30 * 24 * 60;

            return [
                "fyRegionBank" => $ttl > 0 ? Cache::remember($cacheKey, $ttl, $fyRegionBankFunc) : $fyRegionBankFunc()
            ];
        } catch (Exception $exception) {
            handleException($exception);
        }
    }
}
